<!-- src/views/index/IndexView.vue -->
<template>
  <div class="dashboard-container">
    <!-- 统计卡片区域 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card" @click="goToPage('/order')">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: 'rgba(64, 158, 255, 0.1)' }">
              <el-icon class="icon" color="#409eff"><Document /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.paidOrders }}</div>
              <div class="stat-label">已支付订单</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card" @click="goToPage('/feedback')">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: 'rgba(230, 162, 60, 0.1)' }">
              <el-icon class="icon" color="#e6a23c"><ChatLineSquare /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.pendingFeedbacks }}</div>
              <div class="stat-label">待处理反馈</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card" @click="goToPage('/report')">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: 'rgba(245, 108, 108, 0.1)' }">
              <el-icon class="icon" color="#f56c6c"><Warning /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.pendingReports }}</div>
              <div class="stat-label">待处理举报</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card" @click="goToPage('/abnormal')">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: 'rgba(144, 147, 153, 0.1)' }">
              <el-icon class="icon" color="#909399"><CircleClose /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.pendingAbnormals }}</div>
              <div class="stat-label">待处理异常</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近记录区域 -->
    <el-row :gutter="20" class="recent-row">
      <el-col :span="12">
        <el-card class="recent-card">
          <template #header>
            <div class="card-header">
              <span>最近订单</span>
              <el-button link type="primary" @click="goToPage('/order')">查看更多</el-button>
            </div>
          </template>
          <el-table :data="recentOrders" style="width: 100%">
            <el-table-column type="index" />
            <el-table-column prop="orderId" label="订单ID" />
            <el-table-column prop="productName" label="商品名称" />
            <el-table-column prop="paymentTime" label="支付时间">
              <template #default="scope">
                {{ formatDate(scope.row.paymentTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="paymentStatus" label="状态">
              <template #default="scope">
                <el-tag type="success">已支付</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card class="recent-card">
          <template #header>
            <div class="card-header">
              <span>待处理事项</span>
              <el-button link type="primary" @click="goToPage('/'+ activeTab)">查看详情</el-button>
            </div>
          </template>
          <el-tabs v-model="activeTab">
            <el-tab-pane label="反馈" name="feedback">
              <el-table :data="pendingFeedbacks" style="width: 100%" size="large">
                <el-table-column type="index" />
                <el-table-column prop="feedbackId" label="反馈ID" />
                <el-table-column prop="userName" label="用户" />
                <el-table-column prop="createdAt" label="提交时间">
                  <template #default="scope">
                    {{ formatDate(scope.row.createdAt) }}
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="举报" name="report">
              <el-table :data="pendingReports" style="width: 100%" size="large">
                <el-table-column type="index" />
                <el-table-column prop="reportId" label="举报ID" />
                <el-table-column prop="reportType" label="类型" />
                <el-table-column prop="createdAt" label="提交时间">
                  <template #default="scope">
                    {{ formatDate(scope.row.createdAt) }}
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="异常" name="abnormal">
              <el-table :data="pendingAbnormals" style="width: 100%" size="large">
                <el-table-column type="index" class-name="" />
                <el-table-column prop="abnormalId" label="异常ID" />
                <el-table-column prop="abnormalType" label="类型" />
                <el-table-column prop="createdAt" label="发生时间">
                  <template #default="scope">
                    {{ formatDate(scope.row.createdAt) }}
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElNotification } from 'element-plus'
import axios from 'axios'

const router = useRouter()

// 统计数据
const stats = ref({
  paidOrders: 0,
  pendingFeedbacks: 0,
  pendingReports: 0,
  pendingAbnormals: 0
})

// 最近记录
const recentOrders = ref([])
const pendingFeedbacks = ref([])
const pendingReports = ref([])
const pendingAbnormals = ref([])

// 活动标签页
const activeTab = ref('feedback')

// 音频和轮询相关
const pollingTimer = ref(null)
const alertRecords = ref([]) // 存储异常记录的提醒状态
let alertAudio = null

// 跳转到页面
const goToPage = (path) => {
  router.push(path)
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 加载统计数据
const loadStats = async () => {
  try {
    // 获取订单统计数据
    const orderResponse = await axios.get(BASE_URL + '/api/orders/select/all')
    if (orderResponse.data.state === 2001) {
      const orders = orderResponse.data.data
      const paidOrders = orders.filter(order => order.paymentStatus === 'PAID').length
      stats.value.paidOrders = paidOrders
    }

    // 获取反馈统计数据
    const feedbackResponse = await axios.get(BASE_URL + '/api/feedbacks/select', {
      params: {
        pageNum: 1,
        pageSize: 999
      }
    })
    if (feedbackResponse.data.state === 2001) {
      const feedbacks = feedbackResponse.data.data.list || feedbackResponse.data.data
      const pendingFeedbacksCount = Array.isArray(feedbacks)
          ? feedbacks.filter(feedback => feedback.status === 'pending').length
          : 0
      stats.value.pendingFeedbacks = pendingFeedbacksCount
    }

    // 获取举报统计数据
    const reportResponse = await axios.get(BASE_URL + '/api/reports/select', {
      params: {
        pageNum: 1,
        pageSize: 999
      }
    })
    if (reportResponse.data.state === 2001) {
      const reports = reportResponse.data.data.list || reportResponse.data.data
      const pendingReportsCount = Array.isArray(reports)
          ? reports.filter(report => report.status === 'pending').length
          : 0
      stats.value.pendingReports = pendingReportsCount
    }

    // 获取异常统计数据
    const abnormalResponse = await axios.get(BASE_URL + '/api/abnormal-records/select', {
      params: {
        pageNum: 1,
        pageSize: 999
      }
    })
    if (abnormalResponse.data.state === 2001) {
      const abnormals = abnormalResponse.data.data.list || abnormalResponse.data.data
      const pendingAbnormalsCount = Array.isArray(abnormals)
          ? abnormals.filter(abnormal => !abnormal.status || abnormal.status === 'pending').length
          : 0
      stats.value.pendingAbnormals = pendingAbnormalsCount
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
    ElMessage.error('加载统计数据失败: ' + error.message)
  }
}

// 加载最近记录
const loadRecentRecords = async () => {
  try {
    // 加载最近订单
    const orderResponse = await axios.get(BASE_URL + '/api/orders/select/conditions',{
      params: {
        pageNum: 1,
        pageSize: 999
      }
    })
    if (orderResponse.data.state === 2001) {
      const orders = orderResponse.data.data.list
      const paidOrders = orders
          .filter(order => order.paymentStatus === 'PAID')
          .slice(0, 5)
          .map(order => {
            // 获取商品名称（如果需要的话）
            return {
              ...order,
              productName: order.productName || `商品${order.productId}`
            }
          })
      recentOrders.value = paidOrders
    }

    // 加载待处理反馈
    const feedbackResponse = await axios.get(BASE_URL + '/api/feedbacks/select', {
      params: {
        pageNum: 1,
        pageSize: 999
      }
    })
    if (feedbackResponse.data.state === 2001) {
      const feedbacks = feedbackResponse.data.data.list || feedbackResponse.data.data
      const pendingFeedbackList = Array.isArray(feedbacks)
          ? feedbacks.filter(feedback => feedback.status === 'pending').slice(0, 5)
          : []
      // 修复：正确赋值给 pendingFeedbacks.value
      pendingFeedbacks.value = pendingFeedbackList
    }

    // 加载待处理举报
    const reportResponse = await axios.get(BASE_URL + '/api/reports/select', {
      params: {
        pageNum: 1,
        pageSize: 999
      }
    })
    if (reportResponse.data.state === 2001) {
      const reports = reportResponse.data.data.list || reportResponse.data.data
      const pendingReportsList = Array.isArray(reports)
          ? reports.filter(report => report.status === 'pending').slice(0, 5)
          : []
      // 修复：正确赋值给 pendingReports.value
      pendingReports.value = pendingReportsList
    }

    // 加载待处理异常
    const abnormalResponse = await axios.get(BASE_URL + '/api/abnormal-records/select', {
      params: {
        pageNum: 1,
        pageSize: 999
      }
    })
    if (abnormalResponse.data.state === 2001) {
      const abnormals = abnormalResponse.data.data.list || abnormalResponse.data.data
      const pendingAbnormalsList = Array.isArray(abnormals)
          ? abnormals.filter(abnormal => !abnormal.status || abnormal.status === 'pending').slice(0, 5)
          : []
      // 修复：正确赋值给 pendingAbnormals.value
      pendingAbnormals.value = pendingAbnormalsList
    }
  } catch (error) {
    console.error('加载最近记录失败:', error)
    ElMessage.error('加载最近记录失败: ' + error.message)
  }
}

// 新增：检查新异常记录的函数
const checkNewAbnormalRecords = async () => {
  try {
    const response = await axios.get(BASE_URL + '/api/abnormal-records/select/latest-unprocessed')
    if (response.data.state === 2001 && response.data.data.length > 0) {
      const newRecords = response.data.data

      // 过滤出需要提醒的记录（未提醒过或未查看的）
      const recordsToAlert = newRecords.filter(record => {
        const existingAlert = alertRecords.value.find(alert => alert.abnormalId === record.abnormalId)
        // 如果记录不存在或者存在但未查看且未显示过弹窗，则需要提醒
        return !existingAlert || (!existingAlert.viewed && !existingAlert.alertShown)
      })

      if (recordsToAlert.length > 0) {
        // 更新提醒列表
        recordsToAlert.forEach(record => {
          const existingIndex = alertRecords.value.findIndex(alert => alert.abnormalId === record.abnormalId)
          if (existingIndex >= 0) {
            // 更新现有记录（保持现有状态，不重置viewed状态）
            alertRecords.value[existingIndex] = {
              ...alertRecords.value[existingIndex],
              ...record,
              lastAlertTime: new Date().toISOString()
            }
          } else {
            // 添加新记录，标记为未查看且未播放过音频且未显示过弹窗
            alertRecords.value.push({
              abnormalId: record.abnormalId,
              abnormalType: record.abnormalType,
              reason: record.reason,
              createdAt: record.createdAt,
              viewed: false, // 是否已查看详情
              audioPlayed: false, // 是否已播放过音频
              alertShown: false, // 是否已显示过弹窗 - 新增字段
              lastAlertTime: new Date().toISOString()
            })
          }
        })

        // 显示通知（只对需要播放音频的记录播放）
        recordsToAlert.forEach(record => {
          showAbnormalAlert(record)
        })
      }
    }
  } catch (error) {
    console.error('检查新异常记录失败:', error)
  }
}

// 新增：显示异常记录弹窗
const showAbnormalAlert = (record) => {
  const alertInfo = alertRecords.value.find(alert => alert.abnormalId === record.abnormalId)

  // 如果已经显示过弹窗，则不再显示
  if (alertInfo && alertInfo.alertShown) {
    return
  }

  // 只在首次出现预警时播放音频
  if (alertInfo && !alertInfo.audioPlayed) {
    playAlertSound()
    // 标记音频已播放
    alertInfo.audioPlayed = true
  }

  // 标记弹窗已显示
  if (alertInfo) {
    alertInfo.alertShown = true
  }

  ElNotification({
    title: '新异常记录提醒',
    message: `
      <div>
        <p><strong>异常类型:</strong> ${record.abnormalType}</p>
        <p><strong>异常原因:</strong> ${record.reason}</p>
        <p><strong>发生时间:</strong> ${formatDate(record.createdAt)}</p>
        <button onclick="viewAbnormalDetail(${record.abnormalId})"
                style="margin-top: 10px; padding: 5px 10px; background: #409eff; color: white; border: none; border-radius: 4px; cursor: pointer;">
          查看详情
        </button>
      </div>
    `,
    type: 'warning',
    duration: 0, // 不自动关闭
    dangerouslyUseHTMLString: true,
    onClose: () => {
      // 从提醒列表中移除未查看的记录
      const recordIndex = alertRecords.value.findIndex(r => r.abnormalId === record.abnormalId)
      if (recordIndex >= 0 && !alertRecords.value[recordIndex].viewed) {
        alertRecords.value.splice(recordIndex, 1)
      }
    }
  })
}

// 新增：播放声音提醒
const playAlertSound = () => {
  try {
    if (alertAudio) {
      // 重置音频到开头
      alertAudio.currentTime = 0
      // 尝试播放音频
      const playPromise = alertAudio.play()
      if (playPromise !== undefined) {
        playPromise.catch(error => {
          console.log('音频播放被阻止，需要用户交互:', error)
          // 如果被阻止，添加用户交互事件监听器
          const playOnUserInteraction = () => {
            alertAudio.play().catch(e => console.log('用户交互后音频播放失败:', e))
            // 移除事件监听器
            document.removeEventListener('click', playOnUserInteraction)
            document.removeEventListener('keydown', playOnUserInteraction)
          }
          document.addEventListener('click', playOnUserInteraction, { once: true })
          document.addEventListener('keydown', playOnUserInteraction, { once: true })
        })
      }
    } else {
      console.log('音频对象未初始化')
    }
  } catch (e) {
    console.log('音频播放异常:', e)
  }
}

// 新增：查看异常详情
window.viewAbnormalDetail = (abnormalId) => {
  // 关闭所有通知
  ElNotification.closeAll()

  // 标记该记录为已查看（不再播放声音）
  const recordIndex = alertRecords.value.findIndex(r => r.abnormalId === abnormalId)
  if (recordIndex >= 0) {
    alertRecords.value[recordIndex].viewed = true
    // 注意：这里不修改audioPlayed状态，因为用户点击查看详情时音频应该已经播放过了
  }

  // 跳转到详情页面
  router.push(`/abnormal/process?abnormalId=${abnormalId}`)
}

// 新增：清理过期的提醒记录（避免内存泄漏）
const cleanupExpiredAlerts = () => {
  const now = new Date()
  const expirationTime = 24 * 60 * 60 * 1000 // 24小时

  alertRecords.value = alertRecords.value.filter(alert => {
    const alertTime = new Date(alert.lastAlertTime)
    return now - alertTime < expirationTime
  })
}

onMounted(() => {
  loadStats()
  loadRecentRecords()

  // 初始化音频对象
  try {
    alertAudio = new Audio('/sounds/alert.mp3')
    // 预加载音频
    alertAudio.load()
  } catch (e) {
    console.log('音频初始化失败:', e)
  }

  // 每30秒刷新一次数据
  setInterval(() => {
    loadStats()
    loadRecentRecords()
  }, 30000)

  // 每5秒检查一次新异常记录
  pollingTimer.value = setInterval(() => {
    checkNewAbnormalRecords()
  }, 5000)

  // 每小时清理一次过期提醒
  setInterval(() => {
    cleanupExpiredAlerts()
  }, 60 * 60 * 1000)
})

// 组件卸载前清理定时器
onBeforeUnmount(() => {
  if (pollingTimer.value) {
    clearInterval(pollingTimer.value)
  }
  if (alertAudio) {
    alertAudio.pause()
    alertAudio = null
  }
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
}

.icon {
  font-size: 28px;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.recent-row {
  margin-bottom: 20px;
}

.recent-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 100%;
  width: 525px;
  text-overflow: inherit;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #303133;
  font-size: 16px;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style>